from .base_model import BaseModel
from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone
from .classinfo import ClassInfo
from .class_subject_assignment import ClassSubjectAssignment


class ClassCourse(BaseModel):
    """班级课程表模型，关联班级、教师、学科和上课时间"""
    class_info = models.ForeignKey(ClassInfo, on_delete=models.CASCADE, related_name='class_schedules', verbose_name='班级')
    class_subject = models.ForeignKey(ClassSubjectAssignment, on_delete=models.CASCADE, related_name='class_schedules', verbose_name='班级学科', default=1)
    weekday = models.PositiveSmallIntegerField(default=1, choices=[(1, '周一'), (2, '周二'), (3, '周三'), (4, '周四'), (5, '周五'), (6, '周六'), (7, '周日')], verbose_name='星期几')
    course_period = models.ForeignKey('CoursePeriod', on_delete=models.SET_NULL, null=True, blank=True, related_name='class_courses', verbose_name='课程时间段')

    @property
    def end_time(self):
        """根据开始时间和时长计算结束时间"""
        if self.course_period and self.course_period.end_time:
            return self.course_period.end_time
        elif self.course_period and self.course_period.start_time and hasattr(self.course_period, 'duration'):
            # 将时间转换为分钟数
            total_minutes = self.course_period.start_time.hour * 60 + self.course_period.start_time.minute
            # 添加时长
            total_minutes += self.course_period.duration
            # 转换回小时和分钟
            hours, minutes = divmod(total_minutes, 60)
            # 处理可能的小时溢出（超过24小时的情况）
            hours %= 24
            # 返回结束时间
            return timezone.datetime(1, 1, 1, hours, minutes).time()
        return None

    def __str__(self):
        end_time_str = self.end_time.strftime('%H:%M') if self.end_time else '未知'
        start_time_str = self.course_period.start_time.strftime("%H:%M") if self.course_period and self.course_period.start_time else '未知'
        return f'{self.class_info} 每周{self.get_weekday_display()} {self.course_period.name if self.course_period else "未知时间段"} {start_time_str}-{end_time_str} {self.class_subject.subject.name}'

    class Meta:
        verbose_name = '班级课程表'
        verbose_name_plural = '班级课程表'
        unique_together = ('class_info', 'weekday', 'course_period')